<?php
defined('IN_MAIN') or exit('Invalid Access!');

function image_copy_resize($orig_file, $output_file, $width, $height){
 list($width_orig, $height_orig)=getimagesize($orig_file);
 $img_type=strtolower(substr($orig_file, strrpos($orig_file, ".")+1));
 //resize image
 if(($width==$width_orig && $height==$height_orig) || ($width_orig<$width && $height_orig<$height)){
  $no_need_resize=1;
 }

 if($no_need_resize){//no need resize, copy
  if(!copy($orig_file, $output_file)){
   $err=1;
  }
 }else{
  //resize
  $width_t=$width;
  $height_t=$height;
  $ratio_orig=$width_orig/$height_orig;
  if($width/$height > $ratio_orig){
   $width_t=$height*$ratio_orig;
  }else{
   $height_t=$width/$ratio_orig;
  }
  //resample
  $dtn_t=@imagecreatetruecolor($width_t, $height_t);
  if($img_type=="jpg" || $img_type=="jpeg"){
   $src_t=@imagecreatefromjpeg($orig_file);
  }elseif($img_type=="gif"){
   $transparent = @imagecolorallocate($dtn_t, 255, 255, 255);
   @imagefill($dtn_t, 0, 0, $transparent);
   @imagecolortransparent($dtn_t, $transparent);
   $src_t=@imagecreatefromgif($orig_file);
  }elseif($img_type=="png"){
   $transparent = @imagecolorallocate($dtn_t, 255, 255, 255);
   @imagefill($dtn_t, 0, 0, $transparent);
   @imagecolortransparent($dtn_t, $transparent);
   $src_t=@imagecreatefrompng($orig_file);
  }
  if(!$dtn_t || !$src_t){
   $err=1;
  }elseif(!@imagecopyresampled($dtn_t, $src_t, 0, 0, 0, 0, $width_t, $height_t, $width_orig, $height_orig)){
   $err=1;
  }
  if(!$err){
   // Output image
   if($img_type=="jpg" || $img_type=="jpeg"){
    if(!@imagejpeg($dtn_t, $output_file, 85)){
     $err=1;
    }
   }elseif($img_type=="gif"){
    if(!@imagegif($dtn_t, $output_file)){
     $err=1;
    }
   }elseif($img_type=="png"){
    if(!@imagepng($dtn_t, $output_file)){
     $err=1;
    }
   }
  }
 }//finish need to resample
 return !$err;
}
?>